<?php
class Mageex_AdvanceSeo_Model_System_Config_Backend_SubmitSitemapCron extends Mage_Core_Model_Config_Data
{

    const CRON_STRING_PATH = 'crontab/jobs/advanceseo_submitsitemap/schedule/cron_expr';
    const CRON_MODEL_PATH = 'crontab/jobs/mageex_submit/run/model';
	
    protected function _afterSave()
    {
        $enabled = $this->getData('groups/sitemap/enable/value');
		
        $time = $this->getData('groups/sitemap/fields/time_start/value');
		
        $frequency = $this->getData('groups/sitemap/fields/frequency_submit/value');
        
        $frequencyDaily 	= Mageex_AdvanceSeo_Model_System_Config_Source_FrequencySubmit::CRON_DAILY;
        $frequencyWeekly 	= Mageex_AdvanceSeo_Model_System_Config_Source_FrequencySubmit::CRON_WEEKLY;
        $frequencyMonthly 	= Mageex_AdvanceSeo_Model_System_Config_Source_FrequencySubmit::CRON_MONTHLY;
		
		$cronExprArray = array(
			intval($time[1]),                                   # Minute
			intval($time[0]),                                   # Hour
			($frequency == $frequencyMonthly) ? '1' : '*',      # Day of the Month
			'*',                                                # Month of the Year
			($frequency == $frequencyWeekly) ? '1' : '*',       # Day of the Week
		);
		
        $cronExprString = join(' ', $cronExprArray);
        try {
            Mage::getModel('core/config_data')
                ->load(self::CRON_STRING_PATH, 'path')
                ->setValue($cronExprString)
                ->setPath(self::CRON_STRING_PATH)
                ->save();
            Mage::getModel('core/config_data')
                ->load(self::CRON_MODEL_PATH, 'path')
                ->setValue((string) Mage::getConfig()->getNode(self::CRON_MODEL_PATH))
                ->setPath(self::CRON_MODEL_PATH)
                ->save();
        } catch (Exception $e) {
            throw new Exception(Mage::helper('cron')->__('Unable to save the cron expression.'));
        }
    }

}
